/*
 * RCObject.h
 *
 *  Created on: Aug 22, 2014
 *      Author: Lucifer
 */

#ifndef AUTORELEASEPOOL_H_
#define AUTORELEASEPOOL_H_

#include "./REF.h"
#include <vector>

namespace BFX {

class RCObjectPool;

class RCObject {
protected:
	RCObject() {
		_refCount = 0;
	}

public:
	virtual ~RCObject() {
	}

	/**
	 * Increments the reference count for an interface on an object.
	 * @return The method returns the new reference count. This value is intended to be used only
	 * 		for test purposes.
	 */
	long acquireRef() const {
		return (++_refCount);
	}
	/**
	 * Decrements the reference count for an interface on an object.
	 * @return The method returns the new reference count. This value is intended to be used only
	 * 		for test purposes.
	 */
	long releaseRef() const {
		if ((--_refCount) == 0) {
			delete this;
			return 0;
		}
		return _refCount;
	}

	RCObject* autoReleaseRef();

	/**
	 * Gets the current reference count.
	 * @return The current reference count.
	 */
	long getRefCount() const {
		return _refCount;
	}

protected:
	mutable long _refCount;
	friend class RCObjectPool;
};

/**
 *
 */
class RCObjectPool {
public:
	/**
	 * Creates an auto-release pool.
	 */
	RCObjectPool();
	virtual ~RCObjectPool();

	/**
	 * Adds a given object to this pool.
	 * @param object
	 */
	void addObject(RCObject* object);
	/**
	 * Clears the pool.
	 */
	void drain();

	/**
	 * The static way to get current auto release pool.
	 * @return The current pool, or NULL if there is no pool created before calling this method.
	 */
	static RCObjectPool* currentPool();

private:
	RCObjectPool* _poolPrev;			// The previous pool instance.
	std::vector<REF<RCObject> > _objects;
};

} /* namespace BFX */

#endif /* AUTORELEASEPOOL_H_ */
